package com.macro.mall.portal.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.macro.mall.common.constant.AuthConstant;
import com.macro.mall.common.dto.UserDto;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.HomeMemberInfo;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.util.StpMemberUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;

    @Resource
    private RedisTemplate redisTemplate;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Value("${redis.userInfoInitPre.userInfoUserNamePre}")
    private String REDIS_KEY_PREFIX_USER_INFO_USER_NAME_PRE;

    @Value("${redis.userInfoInitPre.userInfoUserPhonePre}")
    private String REDIS_KEY_PREFIX_USER_INFO_USER_PHONE_PRE;


    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<UmsMember> getAllUser() {

        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andIdIsNotNull();
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        return memberList;
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            Asserts.fail("验证码错误");
        }

        //布隆过滤器校验，无是绝对无，有是可能有
        if(checkWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_NAME_PRE,username)) {
            Asserts.fail("该用户已经存在");
        }
        if(checkWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_PHONE_PRE,telephone)) {
            Asserts.fail("该手机号已使用");
        }


      /*  //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }*/
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(BCrypt.hashpw(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);

        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        setWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_NAME_PRE, username);
        setWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_PHONE_PRE, telephone);

        umsMember.setPassword(null);
    }

    /**
     * 查询布隆过滤器中是否存在
     */
    public boolean checkWithBloomFilter(String checkItem, String key) {
        int hashValue = Math.abs(key.hashCode());
        long index = (long) (hashValue % Math.pow(2, 32));
        return redisTemplate.opsForValue().getBit(checkItem, index);
    }

    /**
     * 设置布隆过滤器中是否存在
     */
    public boolean setWithBloomFilter(String checkItem, String key) {
        int hashValue = Math.abs(key.hashCode());
        long index = (long) (hashValue % Math.pow(2, 32));
        return redisTemplate.opsForValue().setBit(checkItem, index, true);
    }


    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone, sb.toString());
        return sb.toString();
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            Asserts.fail("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(BCrypt.hashpw(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        UserDto userDto = (UserDto) StpMemberUtil.getSession().get(AuthConstant.STP_MEMBER_INFO);
        UmsMember member = memberCacheService.getMember(userDto.getId());
        if (member != null) {
            return member;
        } else {
            member = getById(userDto.getId());
            memberCacheService.setMember(member);
            return member;
        }
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public SaTokenInfo login(String username, String password) {
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            Asserts.fail("用户名或密码不能为空！");
        }
        UmsMember member = getByUsername(username);
        if (member == null) {
            Asserts.fail("找不到该用户！");
        }
        if (!BCrypt.checkpw(password, member.getPassword())) {
            Asserts.fail("密码不正确！");
        }
        if (member.getStatus() != 1) {
            Asserts.fail("该账号已被禁用！");
        }
        // 登录校验成功后，一行代码实现登录
        StpMemberUtil.login(member.getId());
        UserDto userDto = new UserDto();
        userDto.setId(member.getId());
        userDto.setUsername(member.getUsername());
        userDto.setClientId(AuthConstant.PORTAL_CLIENT_ID);
        // 将用户信息存储到Session中
        StpMemberUtil.getSession().set(AuthConstant.STP_MEMBER_INFO, userDto);
        // 获取当前登录用户Token信息
        return StpUtil.getTokenInfo();
    }

    @Override
    public void logout() {
        //先清空缓存
        UserDto userDto = (UserDto) StpMemberUtil.getSession().get(AuthConstant.STP_MEMBER_INFO);
        memberCacheService.delMember(userDto.getId());
        //再调用sa-token的登出方法
        StpMemberUtil.logout();
    }

    @Override
    public HomeMemberInfo statisticalMemberInfo() {
        HomeMemberInfo homeMemberInfo=new HomeMemberInfo();
        DateTime today = DateUtil.parse(DateUtil.now());

        //今日 昨日 本月 总会员
        CompletableFuture<Void> todayFuture = CompletableFuture.runAsync(() -> {
            StatisticalMemberInfoParam  statisticalMemberInfoParam=new StatisticalMemberInfoParam();
            statisticalMemberInfoParam.setStartTime(DateUtil.beginOfDay(today).getTime());
            statisticalMemberInfoParam.setEndTime(DateUtil.endOfDay(today).getTime());
            homeMemberInfo.setTodayMemberNum(Long.toString(memberMapper.statisticalMemberInfo( statisticalMemberInfoParam)));

        });
        DateTime yesterday = DateUtil.yesterday();
        CompletableFuture<Void> yesterdayFuture = CompletableFuture.runAsync(() -> {
            StatisticalMemberInfoParam  statisticalMemberInfoParam=new StatisticalMemberInfoParam();
            statisticalMemberInfoParam.setStartTime(DateUtil.beginOfDay(yesterday).getTime());
            statisticalMemberInfoParam.setEndTime(DateUtil.endOfDay(yesterday).getTime());
            homeMemberInfo.setYesterdayMemberNum(Long.toString(memberMapper.statisticalMemberInfo( statisticalMemberInfoParam)));

        });

        CompletableFuture<Void> monthFuture = CompletableFuture.runAsync(() -> {
            StatisticalMemberInfoParam  statisticalMemberInfoParam=new StatisticalMemberInfoParam();
            statisticalMemberInfoParam.setStartTime(DateUtil.beginOfMonth(today).getTime());
            statisticalMemberInfoParam.setEndTime(DateUtil.endOfMonth(today).getTime());
            homeMemberInfo.setMonthMemberNum(Long.toString(memberMapper.statisticalMemberInfo( statisticalMemberInfoParam)));

        });

        CompletableFuture<Void> allFuture = CompletableFuture.runAsync(() -> {
            StatisticalMemberInfoParam  statisticalMemberInfoParam=new StatisticalMemberInfoParam();
            homeMemberInfo.setAllMemberNum(Long.toString(memberMapper.statisticalMemberInfo( statisticalMemberInfoParam)));
        });

        todayFuture.join();
        yesterdayFuture.join();
        monthFuture.join();
        allFuture.join();

        return homeMemberInfo;

    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone) {
        if (StringUtils.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
